package com.tg.appcommon.android;

import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;

import com.tange.base.toolkit.StringUtils;

import java.io.File;
import java.io.IOException;

public class MediaPlayerHelper {
    private MediaPlayer mediaPlayer;
    public MediaPlayerHelper(){
    }

    public void releaseMediaPlayer() {
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    public void playSound(String play) {
        if (!StringUtils.isUrl(play)){
            File file = new File(play);
            if (!file.exists() || !file.isFile() || file.length() <= 0) {
                return;
            }
            TGLog.d("playSound =" + file.getAbsolutePath());
        }

        resetMediaPlayer();
        try {
            mediaPlayer.setDataSource(play);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            startMediaPlayerAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void resetMediaPlayer(){
        if (mediaPlayer == null){
            mediaPlayer = new MediaPlayer();
        }
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.reset();
        }
    }

    private void startMediaPlayerAsync(){
        // 通过异步的方式装载媒体资源
        mediaPlayer.prepareAsync();
        mediaPlayer.setOnPreparedListener(mp -> {
            // 装载完毕回调
            mediaPlayer.start();
        });
        mediaPlayer.setOnCompletionListener(player -> releaseMediaPlayer());
    }

    public void playAssetsSound(String name) {
        resetMediaPlayer();
        try {
            AssetFileDescriptor assetFileDescriptor = TGApplicationBase.getApplication().getAssets().openFd(name);
            mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(), assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());//设置音源//打开音乐文件
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            startMediaPlayerAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
